﻿
using Castle.Core.Internal;
using Coldairarrow.Business.Interface;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using Microsoft.Extensions.Options;
using NetTopologySuite.Index.HPRtree;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.IO;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Net;
using System.Reflection.Metadata;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Coldairarrow.Business.Interface
{
    public class JDL_StockInterfaceBusiness : JDLInterface_BaseBusiness, IJob_Business, ITransientDependency
    {
        //接口信息
        public Base_InterfaceOption JDL_Query;
        public JDL_StockInterfaceBusiness()
        {
            this.InterfaceName = "JDL库存";
            //索引字段
            this.MapFields = GetMapField("JDL_Query");

            //获取此接口的所有API信息
            this.interfaceOption = SqlDb.GetListBySql<Base_InterfaceOption>(@$"SELECT * FROM  Base_InterfaceOption(NOLOCK) WHERE Name='{InterfaceName}' ");
            JDL_Query = this.interfaceOption.Where(x => x.OperateType == "JDL_Query").First();

            //查询执行前的事件
            this.BeforeQueryEvent += InterfaceBusiness_BeforeQueryEvent;
            //查询执行中的事件
            this.OnQueryEvent += InterfaceBusiness_OnQueryEvent;
            //查询执行中的事件
            this.AfterQueryEvent += InterfaceBusiness_AfterQueryEvent;

            //执行非查询请求中的事件
            this.OnNoQueryEvent += InterfaceBusiness_OnNoQueryEvent;

        }

        /// <summary>
        /// 执行非查询请求中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="JDL_NoQueryEventArgs"></param>
        private void InterfaceBusiness_OnNoQueryEvent(object sender, JDL_NoQueryEventArgs JDL_NoQueryEventArgs)
        {
        }

        /// <summary>
        /// 查询执行前的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private async void InterfaceBusiness_BeforeQueryEvent(object sender, JDL_QueryEventArgs queryEventArgs)
        {
            try
            {
                //设置请求头参数
                this.SqlDb._conStrings[0] = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
                var parList = this.SqlDb.GetListBySql<Base_ConfigParameter>(@$"SELECT * FROM  Base_ConfigParameter(NOLOCK) WHERE Code='JDL'");

                queryEventArgs.UrlQuery.AppKey = parList.Where(x => x.Name == "AppKey").First().Value;
                queryEventArgs.UrlQuery.AppSecret = parList.Where(x => x.Name == "AppSecret").First().Value;
                queryEventArgs.UrlQuery.AccessToken = parList.Where(x => x.Name == "AccessToken").First().Value;
                queryEventArgs.UrlQuery.Pin = parList.Where(x => x.Name == "pin").First().Value;
                queryEventArgs.UrlQuery.OwnerNo = parList.Where(x => x.Name == "ownerNo").First().Value;
                queryEventArgs.UrlQuery.Path = JDL_Query.InterfaceType;
                queryEventArgs.UrlQuery.Url = JDL_Query.TargetUrl;
                //设置查询第几页
                queryEventArgs.Page.PageIndex = 1;
                //设置查询第几页
                queryEventArgs.Page.PageSize = queryEventArgs.APINodes.Where(x => x.TargetField == "pageSize").First().SourceField.ToInt();
                //查询的总天数
                //queryEventArgs.Page.Total = queryEventArgs.APINodes.Where(x => x.TargetField == "beginTime").First().Notes.ToInt();
            }
            catch (Exception ex)
            {

            }


        }

        /// <summary>
        /// 查询中的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_OnQueryEvent(object sender, JDL_QueryEventArgs queryEventArgs)
        {
            try
            {
                //获取请求的数据
                JDL_ReqDTO data = new JDL_ReqDTO();
                data.pin = "lizhihong0101";
                data.pin = "lizhihong0101";
                data.ownerNo = "CBU30806325617261";
                data.warehouseNo = "800016965";
                data.currentPage = 1;
                string body = GetJsonData(queryEventArgs.APINodes, queryEventArgs.ParentNode, data);
                body = $"[\"{data.pin}\",{body}]";
                string date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                var sign = GetSign("md5-salt", queryEventArgs.UrlQuery.AppSecret, queryEventArgs.UrlQuery.AccessToken, queryEventArgs.UrlQuery.AppKey, queryEventArgs.UrlQuery.Path, body, date);
                queryEventArgs.HttpClient.Url = GetQueryUrl(queryEventArgs.UrlQuery.Url, queryEventArgs.UrlQuery.AppKey, "CLPS", queryEventArgs.UrlQuery.AccessToken, date,sign, "md5-salt");
                queryEventArgs.reqData = body;
            }
            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }

        /// <summary>
        /// 查询执行后的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_AfterQueryEvent(object sender, JDL_QueryEventArgs queryEventArgs)
        {

            try
            {
                //将查询后的数据转换成对应格式的数据
                JDL_Stock result = (JDL_Stock)JsonConvert.DeserializeObject<JDL_Stock>(queryEventArgs.ResultStr);
                if (result.code == 0)
                {
                    //JDL_OrderLIstDTO_Data DTO_data = (JDL_OrderLIstDTO_Data)JsonConvert.DeserializeObject<JDL_OrderLIstDTO_Data>(result.biz_content);
                    //查询数量小于单页最大数量,当日数据查询完成
                    //if (result.data.orderList.Count < queryEventArgs.Page.PageSize)
                    //{


                    //    //如果所有查询天数小于等于7，查询完成（接口只能查询7天内的数据，如果大于7点的数据需要分批查询）
                    //    if (queryEventArgs.Page.Total <= 7)
                    //    {
                    //        queryEventArgs.Page.Complete = true;
                    //    }
                    //    else
                    //    {
                    //        //7天分批查询
                    //        queryEventArgs.Page.Total = queryEventArgs.Page.Total - 7;
                    //    }
                    //}
                    //else
                    //{
                    //    //继续查询下一页
                    //    queryEventArgs.Page.PageIndex++;
                    //}
                    //queryEventArgs.Rows = result.data.orderList;
                    //queryEventArgs.Success = true;
                }
                else
                {
                    queryEventArgs.Success = false;
                }
                //Thread.Sleep(20000);
            }
            catch (Exception ex)
            {
                queryEventArgs.Success = false;
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
                Thread.Sleep(10000);
            }

        }

        /// <summary>
        /// 执行增删改查业务
        /// </summary>
        public async void ExecuteInterface()
        {
            List<JDL_Stock> QQ = await this.QueryAsync<JDL_Stock>(this.JDL_Query, SqlDb);
        }


        /// <summary>
        /// 任务
        /// </summary>
        public void Job()
        {
            ExecuteInterface();
        }

       


    }

}
